package cn.edu.hncj.service.impl;

import cn.edu.hncj.entity.Account;
import cn.edu.hncj.entity.Book;
import cn.edu.hncj.mapper.BookShopDao;
import cn.edu.hncj.service.BookShopService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Mr.ma
 * @since 2022/11/14 16:12
 **/
@Service
public class BookShopServiceImpl implements BookShopService {
    @Resource
    private BookShopDao bookShopDao;
    @Override
    @Transactional(rollbackFor = {},propagation = Propagation.REQUIRES_NEW)
    public void purchase(String isbn, String username){
        // 1、查询图书
        Book book = bookShopDao.findBookByIsbn(isbn);
        // 2、判断该书库存是否大于0，如果大于，修改库存，库存减一，否则抛出异常
        int stock = bookShopDao.findBookStockByIsbn(isbn);
        if (stock > 0){
            bookShopDao.updateStockByIsbn(isbn);
        } else {
            throw new RuntimeException(book.getBookName() + "库存不足");
        }
        // 3、获取账号余额，如果余额大于售价，则购买成功，余额减去售价，否则抛出异常
        Account account = bookShopDao.findAccountByUsername(username);
        if (account.getBalance() >= Integer.valueOf(book.getPrice())){
            bookShopDao.updateBalanceByUsername(username,Integer.valueOf(book.getPrice()));
        } else {
            throw new RuntimeException(account.getUsername() + "的账户余额不足");
        }
    }

    @Override
    @Transactional(rollbackFor = {})
    public void buy(List<String> isbnList, String username){
        for (String isbn : isbnList) {
            purchase(isbn,username);
        }
    }
}
